package com.lx.jobLaunchDemo;

import org.springframework.batch.core.*;
import org.springframework.batch.core.configuration.JobRegistry;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.batch.core.launch.NoSuchJobException;
import org.springframework.batch.core.repository.JobExecutionAlreadyRunningException;
import org.springframework.batch.core.repository.JobInstanceAlreadyCompleteException;
import org.springframework.batch.core.repository.JobRestartException;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Map;

/**
 * @author lixing
 * @date 2021/7/13 16:08
 */
@Configuration
public class JobLaunchDemoConfiguration {
    @Autowired
    private JobBuilderFactory jobBuilderFactory;

    @Autowired
    private StepBuilderFactory stepBuilderFactory;

    @Autowired
    private JobLauncher jobLauncher;

    @Autowired
    private JobRegistry jobRegistry;

    private Map<String, JobParameter> jobParameterMap;

    @Bean
    public Job helloWorldJolb(){
        return jobBuilderFactory.get("helloWorldJolb12")
                .start(step1())
                .next(step2())
                .build();
    }

    @Bean
    public Step step2() {
        return stepBuilderFactory.get("222222222")
                .tasklet((stepContribution, chunkContext) -> {
                    System.out.println("22222222222");
                    return RepeatStatus.FINISHED;
                }).build();
    }

    @Bean
    public Step step1() {
        return stepBuilderFactory.get("11111111111")
                .tasklet((stepContribution, chunkContext) -> {
                    System.out.println("11111111111");
                    return RepeatStatus.FINISHED;
                }).build();
    }

   public void test() throws NoSuchJobException, JobParametersInvalidException, JobExecutionAlreadyRunningException, JobRestartException, JobInstanceAlreadyCompleteException {
       JobParametersBuilder builder = new JobParametersBuilder();
       JobParameters jobParameters = builder.addString("jobParam", "xxx").toJobParameters();
       Job job = jobRegistry.getJob("xxxx");
       jobLauncher.run(job,jobParameters);
   }
}
